<template>
  <div class="wrapper">
    <div class="city-search">
      <input v-model="searchInputText"
             type="text"
             class="city-search-input"
             placeholder="输入城市名或拼音">
    </div>
    <div class="search-content" ref="wrapper" v-show="searchInputText">
      <ul class="search-list" >
        <li class="border-bottom" v-for="item of searchResult" :key="item.id" @click="handleCityClick">{{ item.name }}</li>
        <li class="border-bottom" v-show="hasMatchData">未搜索到任何内容</li>
      </ul>
    </div>
  </div>

</template>
<script>

  import BScroll from "better-scroll"
  import { mapActions, mapState } from "vuex"

  export default {
    name: "CitySearch",
    data() {
      return {
        cityArray: [],
        searchResult: [],
        scroll: null,
        searchInputText: ""
      }
    },
    props: {
      cities: Object,
    },
    methods: {
      getSearchResult(text) {
        if (this.cityArray.length === 0) {
          return;
        }

        this.searchResult =  this.cityArray.filter((item, index) => {
          if (item.name.includes(text) || item.spell.includes(text)) {
            // console.log(item.name +  ":" + item.spell);
            return true;
          }
          return false;
        });

      },
      handleCityClick(event) {
        this.$store.dispatch("changeCity", event.target.innerText).then();
        this.$router.push("/");
      },
      ...mapActions(['changeCity'])
    },

    computed: {
      hasMatchData() {
        return !this.searchResult.length;
      },
      ...mapState(["city"])
    },
    watch: {
      searchInputText(newText) {
        if (newText.length === 0) {
          return;
        }
        this.getSearchResult(newText);
      },
      cities() {
        console.log("cities change");
        // 此处注意巧妙使用apply函数
        this.cityArray = [].concat.apply([],Object.keys(this.cities).map(key => this.cities[key]));
      }
    },
    mounted() {
      console.log("create scroll");
      this.scroll = new BScroll(this.$refs.wrapper, {
        click: true
      });
    },
    updated() {
      console.log("updated")
    }
  }
</script>

<style scoped lang="scss">
  @import "~styles/variables.scss";
  .city-search {
    background-color: $bgColor;
    padding: 0 0.1rem;
    box-sizing: border-box;
    height: 0.72rem;
    .city-search-input {
      width: 100%;
      box-sizing: border-box;
      padding: 0 .1rem;
      height: .62rem;
      border-radius: .06rem;
      line-height: .62rem;
      color: #666;
      text-align: center;
    }
  }

  .border-bottom {
    &:before {
      border-color: #CCC;
    }
  }

  .search-content {
    position: absolute;
    top: 1.58rem;
    left: 0;
    right: 0;
    bottom: 0;
    overflow: hidden;
    background-color: #eee;
    z-index: 1;
    .search-list {
      li {
        line-height: .6rem;
        text-indent: .2rem;
        color: #666;
        background-color: #ffffff;
      }
    }
  }
</style>